import {host,port} from "../configfile/config.js"
$(function() {
    const baseURL = "http://" + host + ":" + port
    const file_type=["csv","json"]
    const dbname = $(document).attr('title')
    var pageCount = 5 // 页面显示的分页个数
    let getdata_list = { "current": 1, "dbname": dbname, "kwd": "" }
    var r
    var list
    var size = 20; //每页显示九条数据
    var page //总共可以分的页数
    var pageCount = 5 // 页面显示的分页个数
    var Current

    //刷新页面
    function resetUI() {
        r = getDataList(getdata_list)
        list = r.list
        page = r.page //总共可以分的页数
        Current = r.current
        get_content(list);
        get_page(page, Current, pageCount);
    }

    resetUI()

    // data中保存current当前页码以及查询时使用的数据
    function getDataList(data) {
        let url_current = baseURL + "/getData"
        let response = {}
        $.ajax({
            type: "GET",
            async: false,
            ContentType: "application/json",
            data: data,
            url: url_current,
            success: function(res) {
                response.list = res.data
                response.current = res.current
                response.page = res.page
            }
        })
        return response
    }

    //根据选中的页码显示特定的内容
    function get_content(list) {
        let rows = []
        $(".main .card-columns").empty();
        $(list).each(function(index, item) {
            // var tr = '<tr>\
            //             <td class="col-sm-1 id">' + item.id + '</td>\
            //             <td class="col-sm-1 author">' + item.author + '</td>\
            //             <td class="col-sm-1 source">' + item.source + '</td>\
            //             <td class="row col-sm-2 num">\
            //                 <div class="col-sm-6 pubTime">' + item.pubTime + '</div>\
            //                 <div class="col-sm-3 retweetNumber">' + item.retweetNumber + '</div>\
            //                 <div class="col-sm-3 reviewNumber">' + item.reviewNumber + '</div>\
            //             </td>\
            //             <td class="col-sm-2 authorLink">' + item.authorLink + '</td>\
            //             <td class="col-sm-3 mainText">' + item.mainText + '</td>\
            //         </tr>';
            let text = ''
            $.each(item.mainText.split("。"),function(i,v){
                text += '<p class="card-text" style="text-indent:2em;">'+v+'</p>'
                if(i === 4){
                    text+='<p class="card-text" style="text-indent:2em;">...</p>'
                    return false
                }
            })
            // let tr = '<div class="card" id="'+item.gid+'">\
            //             <div class="card-header row no-gutters">\
            //                 <div class="col-md-4">\
            //                     <img src="../static/img/photo.png" class="card-img" alt="...">\
            //                 </div>\
            //                 <div class="col-md-8">\
            //                     <div class="card-body" style="padding-top:5px">\
            //                     <span style="display: inline-block;max-width:80%;height: 30px;overflow: hidden;"><h4>'+item.author+'</h4></span>\
            //                     <!-- <img src="../static/img/blue.png" alt="4" style="margin-left: 4px;position: absolute;width: 12px;top: 1.8rem;"> -->\
            //                     <p class="card-text" style="margin-bottom:3px"><small class="text-muted">来源：'+item.source+'</small></p>\
            //                     <p class="card-text"><small class="text-muted">时间：'+item.pubTime+'</small></p>\
            //                     </div>\
            //                 </div>\
            //             </div>\
            //             <!-- <img class="card-img-top" src="../static/img/photo.png" alt="Card image cap"> -->\
            //             <div class="card-body p-3">\
            //                 '+text+'\
            //             </div>\
            //             <div class="card-footer" style="display: flex;">\
            //                 <small class="text-muted retweetNumber" style="text-align: center;flex: 1;display: inline-block; width: 100%;">'+item.retweetNumber+'</small>\
            //                 <small class="text-muted reviewNumber" style="text-align: center;flex: 1;display: inline-block; width: 100%;">'+item.reviewNumber+'</small>\
            //                 <small class="text-muted likeNumber" style="text-align: center;flex: 1;display: inline-block; width: 100%;">'+item.likeNumber+'</small>\
            //             </div>\
            //         </div>\
            //         '
            let tr = `
<div class="card" id="${item.gid}">
    <div class="card-header row no-gutters">
        <div class="col-md-4">
            <img src="../static/img/photo.png" class="card-img" alt="...">
        </div>
        <div class="col-md-8">
            <div class="card-body" style="padding-top:5px">
            <span style="display: inline-block;max-width:80%;height: 30px;overflow: hidden;"><h4>${item.author}</h4></span>
            <!-- <img src="../static/img/blue.png" alt="4" style="margin-left: 4px;position: absolute;width: 12px;top: 1.8rem;"> -->
            <p class="card-text" style="margin-bottom:3px"><small class="text-muted">来源：${item.source}</small></p>
            <p class="card-text"><small class="text-muted">时间：${item.pubTime}</small></p>
            </div>
        </div>
    </div>
    <!-- <img class="card-img-top" src="../static/img/photo.png" alt="Card image cap"> -->
    <div class="card-body p-3">${text}</div>
    <div class="card-footer" style="display: flex;">
        <small class="text-muted retweetNumber" style="text-align: center;flex: 1;display: inline-block; width: 100%;">${item.retweetNumber}</small>
        <small class="text-muted reviewNumber" style="text-align: center;flex: 1;display: inline-block; width: 100%;">${item.reviewNumber}</small>
        <small class="text-muted likeNumber" style="text-align: center;flex: 1;display: inline-block; width: 100%;">${item.likeNumber}</small>
    </div>
</div>
`
            rows.push(tr)
        })
        $(".main .card-columns").append(rows.join(''));
    }

    //获取当前页码下，分页的显示状态
    function get_page(page, current, pageCount) {
        let rows = []
            // 左按钮
        var li = '<li class="pagenumber" id = "page-prev"></li>'
        rows.push(li)
            // 中间按钮
        if (page === 0) {
            alert("请先获取数据")
                // $(location)[0].href = "http://" + host + ":" + port
        } else if (current < 1 || current > page) {
            throw "页码错误";
        } else if (page <= pageCount) {
            // console.log("第一条判断语句");
            for (var i = 1; i < page + 1; i++) {
                li = '<li class="pagenumber" id = "page-' + i + '">' + i + '</li>'
                rows.push(li)
            }
        } else if (current <= pageCount - 1 && page > pageCount) {
            // console.log("第二条判断语句");
            for (var i = 1; i < pageCount + 1; i++) {
                li = '<li class="pagenumber" id = "page-' + i + '">' + i + '</li>'
                rows.push(li)
            }
        } else if (current > page - pageCount + 1) {
            // console.log("第三条判断语句");
            for (var i = page - pageCount + 1; i < page + 1; i++) {
                li = '<li class="pagenumber" id = "page-' + i + '">' + i + '</li>'
                rows.push(li)
            }
        } else {
            // console.log("第四条判断语句");
            var beforeNumber = current - Math.floor((pageCount - 1) / 2)
            var afterNumber = current + Math.ceil((pageCount - 1) / 2)
            for (var i = beforeNumber; i < afterNumber + 1; i++) {
                li = '<li class="pagenumber" id = "page-' + i + '">' + i + '</li>'
                rows.push(li)
            }

        }
        //右按钮
        li = '<li class="pagenumber" id = "page-next"></li>'
        rows.push(li)
        $(".pagenation").empty().append(rows.join(''));
        $(".pagenation #page-" + Current).addClass("active")
        if (Current == 1) {
            $('#page-prev').removeClass("pagenumber")
        }
        if (Current == page) {
            $('#page-next').removeClass("pagenumber")
        }
    }

    //点击页码
    $(".pagenation").on("click", ".pagenumber", function(e) {
        var id = $(this).attr("id").split("-")[1];
        if (id === "prev") {
            getdata_list.current -= 1;
        } else if (id === "next") {
            getdata_list.current += 1;
        } else {
            $(".pagenumber").each(function(i, item) {
                $(item).removeClass("active")
            })
            getdata_list.current = parseInt(id)
        }
        resetUI();
    })

    $(".title").on("click",".down", function(e) {
        let rows = []
        $.each(file_type,function(i,v){
            r = '<li class="list '+v+'">\
                    <span>'+v+'</span>\
                </li>'
            rows.push(r)
        })
        $(".select .file-list ul").empty().append(rows.join(''));
        $(".box").css("z-index", 0)
        $(".shade").css("z-index", 100).css("opacity", 1)
        $(".select").css("transform", "scale(1)")
    })
    $(".select").on("click", ".cancel",function(e) {
        click_cancel()
    })
    function click_cancel(){
        $(".select").css("transform", "scale(0.5)")
        $(".shade").css("z-index", 0).css("opacity", 0)
        $(".box").css("z-index", 1)
    }
    $(".select .file-list ul").on("click", ".list",function(e) {
        click_cancel()
        $(".header .usercenter").removeClass("usercenter").addClass("downing")
        var fileType = $(this).attr("class").split(" ")[1]
        var fileName = dbname
        let url_current = baseURL + "/getFile"
        $.ajax({
            type:"GET",
            url: url_current,
            data:{
                fileType:fileType,
                fileName:fileName
            },
            success:function(res){
                // console.log(res.time);
            }
        })
    })
        // 下载按钮交互效果
    $(".down").on("mouseover", function(e) {
        $(this).css("transform", "scale(1.1)")
        $(this).css("cursor", "pointer")

    })
    $(".down").on("mouseout", function(e) {
        $(this).css("transform", "scale(1)")
    })

    // 搜索数据
    $(".title .search").on("click", function() {
        let k = ""
        let searchtype = $("#search-type option:selected").val()
        if (searchtype == "os"){
            $(".form-horizontal #os input").each(function(i, v) {
                let id = v.id
                let val = v.value
                if (val !== '') {
                    if (id === 'and') {
                        let var_list = val.split(" ")
                        $(var_list).each(function(ii, vv) {
                            k += "(?=.*?" + vv + ")"
                        })
                    } else if (id === 'or') {
                        let var_list = val.split(" ")
                        $(var_list).each(function(ii, vv) {
                            k += "|(?=.*?" + vv + ")"
                        })
                    } else if (id === 'not') {
                        let var_list = val.split(" ")
                        let temp = ""
                        $(var_list).each(function(ii, vv) {
                            temp += vv + "|"
                        })
                        temp = temp.slice(0, -1)
                        k = "^((?!(" + temp + ")).)*(" + k + ")((?!(" + temp + ")).)*$"
                    }
                }
                $(this).val('')
            })
            getdata_list.kwd = "{'mainText': {'$regex': '"+k+"'}}"
        }
        else if (searchtype == "as"){
            let kwd = {}
            if($(".form-horizontal #as textarea").val()){
                let item = $(".form-horizontal #as textarea").val().split("\n")
                $.each(item,(i,v)=>{
                    console.log(v);
                    let reg = /^\w+/
                    let key = v.match(reg)[0]
                    console.log(key);
                    v= v.replace(/^\w+:/,'')
                    // 搜索参数
                    let params =  v.match(/".*?[^\\]"/g)
                    // 布尔连接符
                    let connector = v.replace(/".*?[^\\]"/g,'').replace(/^\s*/,'').replace(/\s*$/,'').split(/\s+/)
                    let stack = [] //存放连接符
                    let k = "" //暂存表达式
                    let luojifu = {"and":"(?=.*?","or":"|","notl":"((?!(","notr":")).)*"}
                    let xx = ""
                    let tempk=""
                    if(connector[0] !== "not" | (connector[0] === "not" && connector.length === 1)){
                        xx = luojifu.and
                        let tempParams = params.shift()
                        console.log(tempParams);
                        if((/\\\"/).test(tempParams)){
                            tempParams = tempParams.replace(/\\\"/,'')
                        }
                        
                        if(connector[0] !== "("){
                            k = xx + tempParams.replace(/"/g,"")+")"
                        }
                        else{
                            tempk = xx + tempParams.replace(/"/g,"")+")"
                        }
                    }
                    let flag = ""
                    console.log("connector");
                    
                    $.each(connector,function(ii,vv){
                        if(vv === "("){
                            stack.push(vv)
                        }
                        else if(vv === ")"){
                            flag = vv
                            if(xx === luojifu.notl){
                                tempk += luojifu.notr
                                k = "^"+tempk+"("+k+")"+tempk+"$"
                            }
                            else{
                                k += (/^\|/).test(tempk)?(tempk.replace(/^\|/,"|(")+")"):("("+tempk+")")
                            }
                            stack.pop
                            tempk = ""
                        }
                        else if(vv == "and"){
                            xx = luojifu[vv]
                            let tempParams = params.shift()
                            if((/\\\"/).test(tempParams)){
                                tempParams = tempParams.replace(/\\\"/,'')
                            }
                            if((/"/g).test(tempParams)){
                                tempk += xx + tempParams.replace(/"/g,"")+")"
                            }
                        }
                        else if(vv == "not"){
                            xx = luojifu[vv+"l"]
                            tempk += xx
                            let tempParams = params.shift()
                            if((/\\\"/).test(tempParams)){
                                tempParams = tempParams.replace(/\\\"/,'')
                            }
                            if((/"/g).test(tempParams)){
                                tempk += tempParams.replace(/"/g,"")
                            }
                        }
                        else if(vv == "or"){
                            if(xx !== luojifu.notl){
                                let tempParams = params.shift()
                                if((/\\\"/).test(tempParams)){
                                    tempParams = tempParams.replace(/\\\"/,'')
                                }
                                if((/"/g).test(tempParams)){
                                    tempk += luojifu.or +xx + tempParams.replace(/"/g,"")+")"
                                }
                            }
                            else{
                                let tempParams = params.shift()
                                if((/\\\"/).test(tempParams)){
                                    tempParams = tempParams.replace(/\\\"/,'')
                                }
                                if((/"/g).test(tempParams)){
                                    tempk += luojifu.or + tempParams.replace(/"/g,"")
                                }
                            }
                        }
                    })
                    if(flag !== ")"){
                        if(xx === luojifu.notl){
                            tempk += luojifu.notr
                            k = "^"+tempk+"("+k+")"+tempk+"$"
                        }
                        else{
                            k += (/^\|/).test(tempk)?(tempk.replace(/^\|/,"|(")+")"):("("+tempk+")")
                        }
                    }
                    console.log(k);
                    
                    kwd[key] = {'$regex': k}
                })
                
                console.log(kwd);
                // mainText: ("5\"6" or "10") not ("123" or "a b c")
                console.log(JSON.stringify(kwd));
                getdata_list.kwd = JSON.stringify(kwd)
            }
            else{
                getdata_list.kwd = ""
            }
        }
        getdata_list.current = 1
        resetUI()
    })

    $(".header .main li").on("click", function() {
        var path = $(this).attr("id")
        $(location)[0].href = "http://" + host + ":" + port + "/" + dbname + "/" + path
    })

    $(".card-columns").on("mouseover",".card",function(){
        $(this).css("box-shadow", "1px 1px 10px 1px #979797").css("cursor","pointer")
    })
    $(".card-columns").on("mouseout",".card",function(){
        $(this).css("box-shadow", "")
    })
    $(".card-columns").on("click",".card",function(){
        let gid = $(this).attr("id")
        $(location)[0].href = "http://" + host + ":" + port + "/" + dbname + "/dataset/" +gid
    })

    function getDownTaskStatus(d){
        
        let url_current = baseURL + "/downTaskStatus"
        let result = {}
        $.ajax({
            type:"GET",
            url: url_current,
            async: false,
            data:{
                status:d
            },
            success:function(res){
                if(d==="stop"){
                    result["task"] = res.task
                    result["flag"] = res.flag
                }
                else{
                    result["task"] = res.task
                }
            }
        })
        return result
    }

    setInterval(() => {
        let result = getDownTaskStatus("stop")
        let task = result["task"]
        let flag = result["flag"]
        if(task.length){
            let all = "已完成的下载任务\r\n"
            for (let i = 0; i < task.length; i++) {
                all += task[i]["wholename"]+"\r\n"
            }
            if(flag==0){
                $(".header .downing").removeClass("downing").addClass("usercenter")
            }
            alert(all)
        }
    }, 60000);
    
    $(".header .usercenter").on("click",function(){
        click_usercenter()
        $(".box").css("z-index", 0)
        $(".shade").css("z-index", 100).css("opacity", 1)
        $(".select").css("transform", "scale(1)")
    })
    function click_usercenter(){
        let task = getDownTaskStatus("complete")["task"]
        let rows = []
        $.each(task,function(i,v){
            r = '<li class="down-list">\
                    <div class="download name">'+String(v.wholename)+'</div>\
                    <div class="download size">'+v.size+'</div>\
                    <div class="download status">'+v.status+'</div>\
                    <div class="download-button down"></div>\
                    <div class="download-button delete"></div>\
                </li>'
            rows.push(r)
        })
        $(".select .file-list ul").empty().append(rows.join(''));
    }
    $(".select .file-list ul").on("click",".down",function(){
        let fileName = $(this).siblings(".name")[0].innerText
        // click_cancel()
        let url_current = baseURL + "/down?fileName="+fileName
        var downloadLink = document.createElement("a");
        downloadLink.href = url_current
        downloadLink.click();
    })
    $(".select .file-list ul").on("click",".delete",function(){
        let fileName = $(this).siblings(".name")[0].innerText
        let url_current = baseURL + "/deletefile"
        $.ajax({
            type:"POST",
            url : url_current,
            contentType: "application/json",
            data:JSON.stringify({fileName:fileName}),
            success:function(res){
                if(res.status == 200){
                    click_usercenter()
                }
                else{
                    alert("删除失败")
                }
            }
        })
    })

    $("#search-type").on("change",function(){
        // as代表高级搜索，os代表普通搜索
        let type = $("#search-type option:selected").val()
        $(".title form>.col-sm-9").each(function(index,item){
            let id = $(item).attr("id")
            if(id == type){
                $("#"+id).css("display","inline-block")
            }
            else{
                $("#"+id).css("display","none")
            }
        })
    })
})
